package dper.study.codes.elasticsearch.service;

import dper.study.codes.elasticsearch.api.CommitESTemplateAPI;
import dper.study.codes.elasticsearch.model.CommitModel;
import dper.study.codes.elasticsearch.utils.EsConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by leichen on 2017/4/19.
 */
public class CommitESService implements CommitESTemplateAPI {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public void init() {
        if (!elasticsearchTemplate.indexExists(EsConst.INDEX_NAME)) {
            elasticsearchTemplate.createIndex(EsConst.COMMIT_TYPE_NAME);
        }
        elasticsearchTemplate.putMapping(CommitModel.class);
    }

    public boolean indexCommitList(List<CommitModel> commitModelList) {
        List<IndexQuery> queries = new ArrayList<IndexQuery>();
        for (CommitModel commitModel : commitModelList) {
            IndexQuery indexQuery = new IndexQueryBuilder().withId(commitModel.getCommitStrId()).withObject(commitModel).build();
            queries.add(indexQuery);
        }
        elasticsearchTemplate.bulkIndex(queries);
        return true;
    }


}
